package com.shuoyue.ycgk.apputis;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.shuoyue.ycgk.R;

import java.util.HashMap;

/**
 * 权限
 * Created by cheng on 2016/10/19.
 */

public class XPermissionUtil {
    /**
     * 回调代码
     */
    public static final int PERMISSIONS_REQUEST_CODE = 0;
    private Activity activity;
    private OnNext onNext;
    private String[] permissions;
    private boolean isRejectionPrompt = false;
    private DialogInterface.OnClickListener negativeButtonOnClickListener;
    public static final int APPLICATION_DETAILS_SETTINGS_RESULT = 20;

    public XPermissionUtil(Activity activity) {
        this.activity = activity;
    }

    /**
     * 构建一个对象
     *
     * @param activity
     * @return
     */
    public static XPermissionUtil build(Activity activity) {
        return new XPermissionUtil(activity);
    }

    public static boolean hasSelfPermissions(Activity activity, String... permissions) {
        return PermissionUtils.hasSelfPermissions(activity, permissions);
    }

    public void checkRun(OnNext onNext, String... permissions) {
        this.onNext = onNext;
        this.permissions = permissions;
        if (PermissionUtils.hasSelfPermissions(activity, permissions)) {
            if (onNext != null) {
                onNext.onNext();
            }
        } else {
            ActivityCompat.requestPermissions(activity, permissions, PERMISSIONS_REQUEST_CODE);
        }
    }

    boolean isShowDialog = false;


    void showSingleRationale(final OnNext request) {
        if (isShowDialog) {
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(activity)
                .setTitle(R.string.permissionApplication)
                .setCancelable(false)
                .setMessage(activity.getString(isRejectionPrompt ? R.string.permissionAppTips : R.string.permissionTips, getPermissionString(activity)))
                .setPositiveButton(R.string.goSetting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isShowDialog = false;
                        if (!PermissionUtils.shouldShowRequestPermissionRationale(activity, permissions)) {
                            // 打开系统应用设置
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.parse("package:" + activity.getPackageName()));
                            intent.addCategory(Intent.CATEGORY_DEFAULT);
                            activity.startActivityForResult(intent, APPLICATION_DETAILS_SETTINGS_RESULT);
                        } else {
                            checkRun(request, permissions);
                        }

                    }
                });
//        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        isShowDialog = false;
//                        if (negativeButtonOnClickListener != null) {
//                            negativeButtonOnClickListener.onClick(dialog, which);
//                        }
//                    }
//                }
        isShowDialog = true;
        dialog.show();

    }

    /**
     * 获取权限文字
     *
     * @param context
     * @return
     */
    private String getPermissionString(Context context) {
        String str = "";
        String tempStr = "";
        HashMap<String, String> hashMap = new HashMap();
        for (int i = 0; i < permissions.length; i++) {

            switch (permissions[i]) {
                case Manifest.permission.CALL_PHONE:
                    tempStr = context.getString(R.string.permission_CallPhone);
                    break;
                case Manifest.permission.CAMERA:
                    tempStr = context.getString(R.string.permission_Camera);
                    break;

                case Manifest.permission.RECORD_AUDIO:
                    tempStr = context.getString(R.string.permission_Microphone);
                    break;

                case Manifest.permission.ACCESS_FINE_LOCATION:
                case Manifest.permission.ACCESS_COARSE_LOCATION:
                    tempStr = context.getString(R.string.permission_Location);
                    break;

                case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                case Manifest.permission.READ_EXTERNAL_STORAGE:
                    tempStr = context.getString(R.string.permission_Storage);
                    break;

                case Manifest.permission.READ_CONTACTS:
                    tempStr = context.getString(R.string.permission_ReadContacts);
                    break;

                case Manifest.permission.WRITE_CONTACTS:
                    tempStr = context.getString(R.string.permission_WriteContacts);
                    break;

                case Manifest.permission.SEND_SMS:
                    tempStr = context.getString(R.string.permission_SendSMS);
                    break;

                case Manifest.permission.READ_SMS:
                    tempStr = context.getString(R.string.permission_ReadSMS);
                    break;


            }
            //判断是否已经改类型字符串
            if (hashMap.get(tempStr) != null) {
                continue;
            }
            hashMap.put(tempStr, tempStr);

            if (permissions.length > 1 && i == permissions.length - 1) {
                str += context.getString(R.string.and) + tempStr;
            } else {
                str += "、" + tempStr;
            }
        }
        if (!TextUtils.isEmpty(str)) {
            str = str.substring(1, str.length());
        }
        return str;
    }

    /**
     * 拨打电话
     *
     * @param phoneNum
     */
    public void callPhone(final String phoneNum) {
        checkRun(new OnNext() {
            @SuppressLint("MissingPermission")
            @Override
            public void onNext() {
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + phoneNum);
                intent.setData(data);
                activity.startActivity(intent);
            }
        }, Manifest.permission.CALL_PHONE);
    }

    /**
     * 获取手机状态
     *
     * @param onNext
     */
    public void phoneState(OnNext onNext) {
        checkRun(onNext, Manifest.permission.READ_PHONE_STATE);
    }

    /**
     * 读取联系人权限
     */
    public void readContacts(OnNext onNext) {
        checkRun(onNext, Manifest.permission.READ_CONTACTS);
    }

    /**
     * 写联系人权限
     *
     * @param onNext
     */
    public void writeContacts(OnNext onNext) {
        checkRun(onNext, Manifest.permission.WRITE_CONTACTS);
    }


    /**
     * 相机权限
     */
    public void camera(OnNext onNext) {
        checkRun(onNext, Manifest.permission.CAMERA);
    }

    /**
     * 录音
     */
    public void recordAudio(OnNext onNext) {
        checkRun(onNext, Manifest.permission.RECORD_AUDIO);
    }

    /**
     * 定位权限
     */
    public void locatton(OnNext onNext) {
        checkRun(onNext, Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION);
    }

    /**
     * 存储权限
     */
    public void storage(OnNext onNext) {
        checkRun(onNext, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    /**
     * 发送短信权限
     */
    public void sendSMS(OnNext onNext) {

    }

    /**
     * 读短信
     */
    public void readSMS(OnNext onNext) {
        checkRun(onNext, Manifest.permission.READ_SMS);
    }


    public void onRequestPermissionsResult(Activity target, int requestCode, int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_CODE:
                if (PermissionUtils.getTargetSdkVersion(target) < 23 && !PermissionUtils.hasSelfPermissions(target, permissions)) {
                    showSingleRationale(onNext);
                    return;
                }
                if (PermissionUtils.verifyPermissions(grantResults)) {
                    if (onNext != null) {
                        onNext.onNext();
                    }
                } else {
                    showSingleRationale(onNext);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 拒绝时提示
     *
     * @param rejectionPrompt
     */
    public void setRejectionPrompt(boolean rejectionPrompt) {
        isRejectionPrompt = rejectionPrompt;
    }

    /**
     * 检查单个权限是否已经被允许
     *
     * @param permission 要申请的权限
     */
    public boolean checkCurPermissionStatus(String permission) {
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(activity, permission);
    }

    /**
     * 设置取消事件
     *
     * @param negativeButtonOnClickListener
     */
    public void setNegativeButtonOnClickListener(DialogInterface.OnClickListener negativeButtonOnClickListener) {
        this.negativeButtonOnClickListener = negativeButtonOnClickListener;
    }

    /**
     * 检查权限回调
     */
    public interface OnNext {
        /**
         * 授权后回调，去系统设置里授权的不回调
         */
        void onNext();
    }
}
